﻿namespace fleetIt.Core
{
    using System;
    using System.Windows.Data;
    using System.IO;
    using System.Net;
    using System.Drawing;

    [ValueConversion(typeof(string), typeof(string))]
    public class ImageCacher : IValueConverter
    {
        #region IValueConverter Members
        static private readonly string AppDataDirectory = String.Format("{0}/ImageCacher/", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            //Check to see if the directory in AppData has been created
            if (!Directory.Exists(AppDataDirectory))
            {
                //Create it
                Directory.CreateDirectory(AppDataDirectory);
            }
            var uri = new Uri((String)value);

            //The full path of the image on the local computer
            var localFile = String.Format("{0}{1}", AppDataDirectory, uri.Segments[uri.Segments.Length - 1]);
            if (!File.Exists(localFile))
            {
                var request = HttpWebRequest.Create(uri);
                var response = (HttpWebResponse)request.GetResponse();
                //check the content type to assert that the file in the uri is an image
                if (!response.ContentType.StartsWith("image"))
                {
                    throw new FileFormatException(uri, String.Format("Uri passed to ImageCacher does not return an image. Content is of type {0}.", response.ContentType));
                }
                //load the image from the stream
                var image = Image.FromStream(response.GetResponseStream());

                //save it
                image.Save(localFile);
            }
            return localFile;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return null;
        }

        #endregion
    }
}
